<script lang="ts" setup>
import axios from '@/axios.js'
import { reactive, ref, h, onMounted } from 'vue'
import { ElNotification } from "element-plus"
import { useRouter } from 'vue-router'
import cookies from 'vue-cookies'

//路由跳转(js跳转方式)
const router = useRouter();
const toPage = (url:string)=>{
   router.push({name:url})    //router.push({path:url})  path方式//router.push(url) 下面传'/xxx'
}

//初始化 + 登录
const codeUrl = ref<string>('/api/user/code')
const resetCode = () => {
  codeUrl.value = codeUrl.value + '?' + Math.random().toFixed(1)
}

//提示框
const login_error = (meg:string) => {
  ElNotification({
    // title: 'Custom Position',
    message: h('i', { style: 'color: teal' }, meg),
    position: 'bottom-left', //top-left
    type:'error',
    offset:0
  })
}
const login_success = (meg:string,is_icon:boolean) => {
  ElNotification({
    // title: 'Custom Position',
    message: h('i', { style: 'color: teal' }, meg),
    position: 'bottom-left', //top-left
    type: is_icon ? 'success' : '',
    duration: 1000,
    onClose: is_icon ? ()=>{ } : ()=>{ toPage('index') }
  })
}

/** 非简化版
    let {data:res} = await axios({
        url: "/user/create",
        method: "POST",
        data: formLabelAlign,
       headers: {
          'Content-Type': "application/json"
       }
     })
 */
const formLabelAlign = reactive({name: '',pwd: '',type: '',})

// let def_name = '1';
// let def_pwd  = '2';
// let def_code = '3';

const check_login = ()=>{
    if(cookies.isKey('name') && cookies.isKey('pwd')) return true;
    return false;
}
const set_defmeg = async () =>{
    if( check_login() ){
      formLabelAlign.name = cookies.get('name')
      formLabelAlign.pwd  = cookies.get('pwd')
      formLabelAlign.type = (await axios.get('/user/defCode').then( (res)=> res.data )).defCode
      // def_name = cookies.isKey('name')
      // def_pwd  = cookies.isKey('pwd')
      // def_code = codeUrl.value
    }
}
onMounted( ()=>{
  set_defmeg();
})

const login = async () =>{
  
     if(!formLabelAlign.name || !formLabelAlign.pwd || !formLabelAlign.type) return false;
     let res = await axios.post('/user/create',formLabelAlign).then( (res:any) => res.data ) //简写
     if(res.error){
           formLabelAlign.type = '';
           cookies.remove('name')
           cookies.remove('pwd')
           resetCode();
           login_error(res.message);
           return;
     }
     
     if(!check_login()){
         cookies.set('name',res.name);
         cookies.set('pwd',res.password);
     }
  
    login_success(`欢迎 ${res.name}`,true)
     resetForm();
     setTimeout(
        ()=>{ 
           login_success('正在为您跳转...', false)
        }
     ,500)
     
     
     /**
      * 全局设置
      * cookies.config('1d') / cookies.config(60 * 60 * 24 * 1,'');
      * 单独设置
      * cookies.set(key, value,"1d / 60*60*24 / new Date(2024, 03, 16)")  
      * 浏览器会话结束时过期
      * cookies.set("default_unit_second","input_value","0");
      * 永不过期
      * this.$cookies.set("default_unit_second","input_value",-1);
      * 
      * cookies.get(key)   
      * cookies.keys()  //获取所有keys 
      * cookies.remove(key) 
      * cookies.isKey(key)
      * 
      */
}

const loginForm = ref();
//重置表单
const resetForm = ()=> {
  loginForm.value.resetFields();
}

</script>

<template>
  <div class="login_box" >
      <div class="login_con">
       <h1 style="text-align: left;">Hello,This is <font style="font-weight: bold;">Login</font> page!</h1>
       <!-- <router-link :to="{name:'login'}" style="margin-right: 10px;">Login</router-link> -->
       <div class="welcome_button">
         <button @click="toPage('login')">Login</button>
         <button @click="toPage('index')">Index</button>
         <button @click="toPage('out')">Logout</button>
      </div>
      <el-form ref="loginForm"  label-position="top" label-width="100px" :model="formLabelAlign" style="max-width: 460px" >
        <el-form-item label="Account" prop="name">
          <el-input v-model="formLabelAlign.name" />
        </el-form-item>
        <el-form-item label="Password" prop="pwd">
          <el-input type="password" v-model="formLabelAlign.pwd" />
        </el-form-item>
        <el-form-item label="Code" prop="type"> 
          <div style="display: flex;">
            <!-- 给验证码输入框绑定回车 -->
            <el-input v-model="formLabelAlign.type"  @keydown.enter="login()"  />  
            <img @click="resetCode"  :src="codeUrl" style="display: block;margin-left:5px;margin-top:-8px">
          </div>
        </el-form-item>
        <el-form-item>
             <el-button @click="login">Login</el-button>
        </el-form-item>
        
      </el-form>
      
      </div>
  </div>
</template>

<style scoped lang="scss">
  
 :deep(.el-input__inner){
   color: #b6b6b6;
 }
 
 :deep(.el-button){
   background-color: #1d1e1e;
   transition: background-color .3s;
   width: 190px;
   border-color: #0e517a;
   color:#ccc
 }
 

 //登录按钮
 :deep(.el-button):hover{
   background-color: #1c2835;
   color:#409eff
 }
 
 //提示框
 :deep(.el-notification) {
   color:#fff
 }

 
   .login_box{
     width: 100%;
     height: 100vh;
     display: flex;
     justify-content: center;
     align-items: center;
     margin-top: -2em;
     
     
     //屏幕高度500px内生效
     @media screen and (max-height:500px) {
         h1 {
            display: none;
         }
     }
     
   }  

  :deep(.el-form-item__label){
    color: #b4b4b4;
  }

  :deep(.el-input__wrapper){
    background-color: transparent
  }
  
  .welcome_button{
    width: 100%;
    display: flex;
    justify-content: stretch;
    
    button{
      margin: 0px 10px 10px 0px;
      height: 40px;
      line-height: 0px;
      color: rgba(255, 255, 255, 0.87);
    }
  }

</style>